﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Core.Contracts.Identity;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Account;
using TomNet.IMSC.Model.ViewModels.Account;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.StaffApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.StaffAPI
{
    [Description("API-业绩")]
    [ApiAuthentication]
    public class StaffSalaryController : BaseApiController
    {
        public IBrokerageRunningsContract BContract { set; get; }// 佣金流水
        public IStaffContract SContract { get; set; }
        public INewHouseRunningsContract NHContract { get; set; }
        public ILowPriceHouseRunningsContract LPHContract { get; set; }
        public IDecorationRunningsContract DContract { get; set; }
        public IFinanceRunningsContract FContract { get; set; }
        public IBrokerageSettleAccountsRunningsContract BSContract { get; set; }
        public IBuildingsBrokerageLevelContract BBLContract { get; set; }
        public IBuildingsBrokerageGroupContract BBGContract { get; set; }
        public IDecorationCompanyBrokerageLevelContract DBLContract { get; set; }
        public IDecorationCompanyBrokerageGroupContract DBGContract { get; set; }
        public IBrokerageTypeContract BTContract { get; set; }
        public ISalaryContract SaContract { get; set; }
        public IExpensesRunningsContract EContract { set; get; }// 费用流水
        public IOutMoneyOrdersContract OMOContract { get; set; }
        public IOutMoneyOrdersRunningsContract OMORContract { get; set; }
        public IOutMoneyAccountContract OMAContract { get; set; }

        public IBuildingsContract BuildingsContract { get; set; }
        public IRoleAuthorityContract RoleAuthorityContract { get; set; }
        public IStaffRolesContract StaffRolesContract { get; set; }
        public IStaffAuthorityContract StaffAuthorityContract { get; set; }
        private bool IsAuthority(int AuthorityID)
        {
            int staffid = BaseWebApiExt.GetStaffIDByToken();
            List<int> al = new List<int>();
            var qa = from a in RoleAuthorityContract.Entities
                     join
                         b in StaffRolesContract.Entities on a.RoleID equals b.RoleID
                     where b.StaffID == staffid
                     select a.AuthorityID;
            al.AddRange(qa.ToList());
            var sa = from a in StaffAuthorityContract.Entities
                     where a.StaffID == staffid
                     select a.AuthorityID;
            al.AddRange(sa.ToList());

            return (from a in al select (a)).Distinct().ToList().Contains(AuthorityID);
        }




        [Description("API-业绩列表")]
        public IHttpActionResult ttGetSalaryList([FromBody]SalaryParamsModel entity)
        {

            IQueryable<Models.StaffApiParams.SalaryListModel> query = Enumerable.Empty<Models.StaffApiParams.SalaryListModel>().AsQueryable();
            DateTime bt = entity.BeginTime;
            DateTime et = entity.EndTime.AddDays(1);
            int staffid = BaseWebApiExt.GetStaffIDByToken();
            switch (entity.ModuleID)
            {
                case 1:
                    query = from sa in SaContract.Entities
                            join n in NHContract.Entities on sa.RunningsID equals n.Id
                            join u1 in SContract.Entities on n.OriginStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on n.SellStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            where sa.ModuleID == entity.ModuleID && sa.UserTypeID == entity.UserTypeID && n.SubscribeTime >= bt && n.SubscribeTime <= et
                            select new Models.StaffApiParams.SalaryListModel
                            {
                                Amount = sa.Amount,
                                MinAmount = sa.MinAmount,
                                CompanyBrokerageState = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault() == null ? 0 : BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault().State,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                Id = sa.Id,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.BuildingName,
                                ItemPrice = n.TotalPrice,
                                ItemTime = n.SubscribeTime,
                                ModuleID = entity.ModuleID,
                                Remark = sa.Remark,
                                RunningsID = sa.RunningsID,
                                SalaryDate = sa.SalaryDate,
                                StaffID = sa.UserTypeID == 1 ? n.OriginStaffID : n.SellStaffID,
                                StaffName = sa.UserTypeID == 1 ? eu1d.Name : eu2d.Name,
                                State = sa.State,
                                CompanyBonus = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 2).FirstOrDefault().Amount,
                                CompanyBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault().Amount,
                                IntermediaryBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 3).FirstOrDefault().Amount,
                                UserBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 4).FirstOrDefault().Amount,
                                Expenses = EContract.Entities.Count(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)) > 0 ? EContract.Entities.Where(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)).Sum(p => p.Amount) : 0,
                                UserName = n.UserName,
                                UserTypeID = sa.UserTypeID
                            };
                    break;
                case 2:
                    query = from sa in SaContract.Entities
                            join n in LPHContract.Entities on sa.RunningsID equals n.Id
                            join u1 in SContract.Entities on n.OriginStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on n.SellStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on n.StationedStaffID equals u3.Id into eu3
                            from eu3d in eu2.DefaultIfEmpty()
                            where sa.ModuleID == entity.ModuleID && sa.UserTypeID == entity.UserTypeID && n.SubscribeTime >= bt && n.SubscribeTime <= et
                            select new Models.StaffApiParams.SalaryListModel
                            {
                                Amount = sa.Amount,
                                MinAmount = sa.MinAmount,
                                CompanyBrokerageState = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault() == null ? 0 : BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault().State,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                Id = sa.Id,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.BuildingName,
                                ItemPrice = n.LowPrice,
                                ItemTime = n.SubscribeTime,
                                ModuleID = entity.ModuleID,
                                Remark = sa.Remark,
                                RunningsID = sa.RunningsID,
                                SalaryDate = sa.SalaryDate,
                                StaffID = sa.UserTypeID == 1 ? n.OriginStaffID : (sa.UserTypeID == 2 ? n.SellStaffID : n.StationedStaffID),
                                StaffName = sa.UserTypeID == 1 ? eu1d.Name : (sa.UserTypeID == 2 ? eu2d.Name : eu3d.Name),
                                State = sa.State,
                                CompanyBonus = 0,
                                CompanyBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 6).FirstOrDefault().Amount,
                                IntermediaryBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 7).FirstOrDefault().Amount,
                                UserBrokerage = 0,
                                Expenses = EContract.Entities.Count(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)) > 0 ? EContract.Entities.Where(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)).Sum(p => p.Amount) : 0,
                                UserName = n.UserName,
                                UserTypeID = sa.UserTypeID
                            };
                    break;
                case 4:
                    query = from sa in SaContract.Entities
                            join n in DContract.Entities on sa.RunningsID equals n.Id
                            join u1 in SContract.Entities on n.OriginStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on n.SellStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            where sa.ModuleID == entity.ModuleID && sa.UserTypeID == entity.UserTypeID && n.SubscribeTime >= bt && n.SubscribeTime <= et
                            select new Models.StaffApiParams.SalaryListModel
                            {
                                Amount = sa.Amount,
                                MinAmount = sa.MinAmount,
                                CompanyBrokerageState = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault() == null ? 0 : BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault().State,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                Id = sa.Id,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.DecorationCompanyName,
                                ItemPrice = n.TotalPrice,
                                ItemTime = n.SubscribeTime,
                                ModuleID = entity.ModuleID,
                                Remark = sa.Remark,
                                RunningsID = sa.RunningsID,
                                SalaryDate = sa.SalaryDate,
                                StaffID = sa.UserTypeID == 1 ? n.OriginStaffID : n.SellStaffID,
                                StaffName = sa.UserTypeID == 1 ? eu1d.Name : eu2d.Name,
                                State = sa.State,
                                CompanyBonus = 0,
                                CompanyBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 9).FirstOrDefault().Amount,
                                IntermediaryBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 10).FirstOrDefault().Amount,
                                UserBrokerage = 0,
                                Expenses = EContract.Entities.Count(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)) > 0 ? EContract.Entities.Where(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)).Sum(p => p.Amount) : 0,
                                UserName = n.UserName,
                                UserTypeID = sa.UserTypeID
                            };
                    break;
                case 5:
                    query = from sa in SaContract.Entities
                            join n in FContract.Entities on sa.RunningsID equals n.Id
                            join u1 in SContract.Entities on n.TransactStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on n.SellStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            where sa.ModuleID == entity.ModuleID && sa.UserTypeID == entity.UserTypeID && n.FilingTime >= bt && n.FilingTime <= et
                            select new Models.StaffApiParams.SalaryListModel
                            {
                                Amount = sa.Amount,
                                MinAmount = sa.MinAmount,
                                CompanyBrokerageState = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault() == null ? 0 : BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 1).FirstOrDefault().State,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                Id = sa.Id,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.FinanceItemsName,
                                ItemPrice = n.Price,
                                ItemTime = n.FilingTime,
                                ModuleID = entity.ModuleID,
                                Remark = sa.Remark,
                                RunningsID = sa.RunningsID,
                                SalaryDate = sa.SalaryDate,
                                StaffID = sa.UserTypeID == 1 ? n.TransactStaffID : n.SellStaffID,
                                StaffName = sa.UserTypeID == 1 ? eu1d.Name : eu2d.Name,
                                State = sa.State,
                                CompanyBonus = 0,
                                CompanyBrokerage = 0,
                                IntermediaryBrokerage = BContract.Entities.Where(p => p.RunningsID == sa.RunningsID && p.ModuleID == sa.ModuleID && p.BrokerageTypeID == 12).FirstOrDefault().Amount,
                                UserBrokerage = 0,
                                Expenses = EContract.Entities.Count(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4))>0?EContract.Entities.Where(p => p.ModuleID == sa.ModuleID && p.RunningsID == sa.RunningsID && (p.State == 2 || p.State == 4)).Sum(p => p.Amount):0,
                                UserName = n.UserName,
                                UserTypeID = sa.UserTypeID
                            };
                    break;
                default:
                    break;
            }
            //if (State > 0)// 状态  0未开    1已开
            //{
            string[] s = entity.State.Split(',');
            query = query.Where(p => s.Contains(p.State.ToString()));
            //}
            query = query.Where(p => p.StaffID == staffid);
            if (!String.IsNullOrEmpty(entity.Search))
            {
                query = query.Where(p => p.ItemName.IndexOf(entity.Search) != -1 || p.IntermediaryName.IndexOf(entity.Search) != -1 || p.UserName.IndexOf(entity.Search) != -1 || p.CustomerName.IndexOf(entity.Search) != -1 || p.CustomerPhone.IndexOf(entity.Search) != -1);
            }

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.pageIndex - 1) * entity.pageSize).Take(entity.pageSize)
                : null;

            List<Models.StaffApiParams.SalaryListModel> ql = total > 0 ? query.ToList() : new List<Models.StaffApiParams.SalaryListModel>();
            if (total > 0)
            {
                foreach (var item in ql.Where(p => p.State == 0))
                {
                    item.Amount = ((item.CompanyBrokerage + item.CompanyBonus - (item.IntermediaryBrokerage * (1 - item.ReturnRate)) - item.UserBrokerage - item.Expenses) * (1 - item.TaxRate) * item.Percentage);
                    if (item.Amount < item.MinAmount)
                    {
                        item.Amount = item.MinAmount;
                    }
                }
            }
            var result = new AjaxResult("成功", AjaxResultType.Success, ql);
            return Token(result, "");

        }


        [Description("API-出款单列表")]
        public IHttpActionResult ttGetOutMoneyOrdersList([FromBody]OutMoneyOrdersParamsModel entity)
        {
            TomNet.IMSC.Model.DbModels.Organization.Staff staff = SContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());
            var query = OMOContract.Entities.Where(p => p.ModuleID == entity.ModuleID && p.AgentID == staff.AgentID).OrderByDescending(p => p.Id);
            var result = new AjaxResult("成功", AjaxResultType.Success, query.ToList());
            return Token(result, "");
        }


        [Description("API-出款单明细列表")]
        public IHttpActionResult ttGetOutMoneyOrdersRunningsList([FromBody]OutMoneyOrdersParamsModel entity)
        {
            int staffid = BaseWebApiExt.GetStaffIDByToken();
            IQueryable<OutMoneyOrdersRunningsListModel> query = Enumerable.Empty<OutMoneyOrdersRunningsListModel>().AsQueryable();
            var om = OMOContract.GetByKey(entity.ID);
            switch (om.ModuleID)
            {
                case 1://新房
                    query = from a in OMORContract.Entities//出款单记录表
                            join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id//出款单表
                            join c in BContract.Entities on a.BrokerageRunningsID equals c.Id//佣金流水表
                            join d in NHContract.Entities on c.RunningsID equals d.Id//新房流水表
                            join e in OMAContract.Entities on a.OutMoneyAccountID equals e.Id into ee//出款帐户
                            join bb in BuildingsContract.Entities on d.BuildingID equals bb.Id//新房楼盘表
                            from eed in ee.DefaultIfEmpty()
                            join f in BTContract.Entities on c.BrokerageTypeID equals f.Id//佣金类型表
                            join u1 in SContract.Entities on a.CreateStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on a.FinanceStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on a.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on a.OutMoneyStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            join u5 in SContract.Entities on a.SysStaffID equals u5.Id into eu5
                            from eu5d in eu5.DefaultIfEmpty()
                            join u6 in SContract.Entities on d.SellStaffID equals u6.Id into eu6
                            from eu6d in eu6.DefaultIfEmpty()
                            where a.OutMoneyOrdersID == om.Id
                            select new OutMoneyOrdersRunningsListModel()
                            {
                                AccountBank = a.AccountBank,
                                AccountNumber = a.AccountNumber,
                                AccountName = a.AccountName,
                                Amount = a.Amount,
                                BrokerageRunningsID = a.BrokerageRunningsID,
                                BrokerageTypeID = c.BrokerageTypeID,
                                BrokerageTypeName = f.Name,
                                BrokerageAmount = c.Amount,
                                BrokerageTax = c.Tax,
                                BrokerageSettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Sum(x => x.a),
                                CreateStaffID = a.CreateStaffID,
                                CreateStaffName = eu1d.Name,
                                CreateTime = a.CreateTime,
                                CustomerName = d.CustomerName,
                                CustomerPhone = d.CustomerPhone,
                                FinanceRemark = a.FinanceRemark,
                                FinanceStaffID = a.FinanceStaffID,
                                FinanceStaffName = eu2d.Name,
                                FinanceState = a.FinanceState,
                                FinanceTime = a.FinanceTime,
                                ID = a.Id,
                                BuildingName = bb.Name,
                                IntermediaryName = d.IntermediaryName,
                                ItemName = d.BuildingName,
                                ItemPrice = d.TotalPrice,
                                ItemTime=d.SubscribeTime,
                                OriginRemark = a.OriginRemark,
                                OriginStaffID = a.OriginStaffID,
                                OriginStaffName = eu3d.Name,
                                OriginState = a.OriginState,
                                OriginTime = a.OriginTime,
                                OutMoneyAccountID = a.OutMoneyAccountID,
                                OutMoneyAccountName = eed.Name,
                                OutMoneyOrdersID = a.OutMoneyOrdersID,
                                OutMoneyRemark = a.OutMoneyRemark,
                                OutMoneyStaffID = a.OutMoneyStaffID,
                                OutMoneyStaffName = eu4d.Name,
                                OutMoneyState = a.OutMoneyState,
                                OutMoneyTime = a.OutMoneyTime,
                                RunningsID = c.RunningsID,
                                StateRemark = "",//GetOutMoneyOrdersRunningsStateRemark(a.FinanceState,a.FinanceRemark,a.OriginState,a.OriginRemark,a.SysState,a.SysRemark,a.OutMoneyState,a.OutMoneyRemark),
                                SysRemark = a.SysRemark,
                                SysStaffID = a.SysStaffID,
                                SysStaffName = eu5d.Name,
                                SysState = a.SysState,
                                SysTime = a.SysTime,
                                UserName = d.UserName,
                                SellStaffID = d.SellStaffID,
                                SellStaffName = eu6d.Name,
                                OrdersState = b.State
                            };
                    break;
                case 2://低价房
                    query = from a in OMORContract.Entities
                            join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id
                            join c in BContract.Entities on a.BrokerageRunningsID equals c.Id
                            join d in LPHContract.Entities on c.RunningsID equals d.Id
                            join e in OMAContract.Entities on a.OutMoneyAccountID equals e.Id into ee
                            from eed in ee.DefaultIfEmpty()
                            join f in BTContract.Entities on c.BrokerageTypeID equals f.Id
                            join u1 in SContract.Entities on a.CreateStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on a.FinanceStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on a.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on a.OutMoneyStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            join u5 in SContract.Entities on a.SysStaffID equals u5.Id into eu5
                            from eu5d in eu5.DefaultIfEmpty()
                            join u6 in SContract.Entities on d.SellStaffID equals u6.Id into eu6
                            from eu6d in eu6.DefaultIfEmpty()
                            where a.OutMoneyOrdersID == om.Id
                            select new OutMoneyOrdersRunningsListModel()
                            {
                                AccountBank = a.AccountBank,
                                AccountNumber = a.AccountNumber,
                                AccountName = a.AccountName,
                                Amount = a.Amount,
                                BrokerageRunningsID = a.BrokerageRunningsID,
                                BrokerageTypeID = c.BrokerageTypeID,
                                BrokerageTypeName = f.Name,
                                BrokerageAmount = c.Amount,
                                BrokerageTax = c.Tax,
                                BrokerageSettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Sum(x => x.a),
                                CreateStaffID = a.CreateStaffID,
                                CreateStaffName = eu1d.Name,
                                CreateTime = a.CreateTime,
                                CustomerName = d.CustomerName,
                                CustomerPhone = d.CustomerPhone,
                                FinanceRemark = a.FinanceRemark,
                                FinanceStaffID = a.FinanceStaffID,
                                FinanceStaffName = eu2d.Name,
                                FinanceState = a.FinanceState,
                                FinanceTime = a.FinanceTime,
                                ID = a.Id,
                                IntermediaryName = d.IntermediaryName,
                                ItemName = d.BuildingName,
                                ItemPrice = d.LowPrice,
                                ItemTime=d.SubscribeTime,
                                OriginRemark = a.OriginRemark,
                                OriginStaffID = a.OriginStaffID,
                                OriginStaffName = eu3d.Name,
                                OriginState = a.OriginState,
                                OriginTime = a.OriginTime,
                                OutMoneyAccountID = a.OutMoneyAccountID,
                                OutMoneyAccountName = eed.Name,
                                OutMoneyOrdersID = a.OutMoneyOrdersID,
                                OutMoneyRemark = a.OutMoneyRemark,
                                OutMoneyStaffID = a.OutMoneyStaffID,
                                OutMoneyStaffName = eu4d.Name,
                                OutMoneyState = a.OutMoneyState,
                                OutMoneyTime = a.OutMoneyTime,
                                RunningsID = c.RunningsID,
                                StateRemark = "",//GetOutMoneyOrdersRunningsStateRemark(a.FinanceState, a.FinanceRemark, a.OriginState, a.OriginRemark, a.SysState, a.SysRemark, a.OutMoneyState, a.OutMoneyRemark),
                                SysRemark = a.SysRemark,
                                SysStaffID = a.SysStaffID,
                                SysStaffName = eu5d.Name,
                                SysState = a.SysState,
                                SysTime = a.SysTime,
                                UserName = d.UserName,
                                SellStaffID = d.SellStaffID,
                                SellStaffName = eu6d.Name,
                                OrdersState = b.State
                            };
                    break;
                case 4://装修
                    query = from a in OMORContract.Entities
                            join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id
                            join c in BContract.Entities on a.BrokerageRunningsID equals c.Id
                            join d in DContract.Entities on c.RunningsID equals d.Id
                            join e in OMAContract.Entities on a.OutMoneyAccountID equals e.Id into ee
                            from eed in ee.DefaultIfEmpty()
                            join f in BTContract.Entities on c.BrokerageTypeID equals f.Id
                            join u1 in SContract.Entities on a.CreateStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on a.FinanceStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on a.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on a.OutMoneyStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            join u5 in SContract.Entities on a.SysStaffID equals u5.Id into eu5
                            from eu5d in eu5.DefaultIfEmpty()
                            join u6 in SContract.Entities on d.SellStaffID equals u6.Id into eu6
                            from eu6d in eu6.DefaultIfEmpty()
                            where a.OutMoneyOrdersID == om.Id
                            select new OutMoneyOrdersRunningsListModel()
                            {
                                AccountBank = a.AccountBank,
                                AccountNumber = a.AccountNumber,
                                AccountName = a.AccountName,
                                Amount = a.Amount,
                                BrokerageRunningsID = a.BrokerageRunningsID,
                                BrokerageTypeID = c.BrokerageTypeID,
                                BrokerageTypeName = f.Name,
                                BrokerageAmount = c.Amount,
                                BrokerageTax = c.Tax,
                                BrokerageSettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == c.Id select new { a = bs.Amount }).Sum(x => x.a),
                                CreateStaffID = a.CreateStaffID,
                                CreateStaffName = eu1d.Name,
                                CreateTime = a.CreateTime,
                                CustomerName = d.CustomerName,
                                CustomerPhone = d.CustomerPhone,
                                FinanceRemark = a.FinanceRemark,
                                FinanceStaffID = a.FinanceStaffID,
                                FinanceStaffName = eu2d.Name,
                                FinanceState = a.FinanceState,
                                FinanceTime = a.FinanceTime,
                                ID = a.Id,
                                IntermediaryName = d.IntermediaryName,
                                ItemName = d.DecorationCompanyName,
                                ItemPrice = d.TotalPrice,
                                ItemTime = d.SubscribeTime,
                                OriginRemark = a.OriginRemark,
                                OriginStaffID = a.OriginStaffID,
                                OriginStaffName = eu3d.Name,
                                OriginState = a.OriginState,
                                OriginTime = a.OriginTime,
                                OutMoneyAccountID = a.OutMoneyAccountID,
                                OutMoneyAccountName = eed.Name,
                                OutMoneyOrdersID = a.OutMoneyOrdersID,
                                OutMoneyRemark = a.OutMoneyRemark,
                                OutMoneyStaffID = a.OutMoneyStaffID,
                                OutMoneyStaffName = eu4d.Name,
                                OutMoneyState = a.OutMoneyState,
                                OutMoneyTime = a.OutMoneyTime,
                                RunningsID = c.RunningsID,
                                StateRemark = "",//GetOutMoneyOrdersRunningsStateRemark(a.FinanceState, a.FinanceRemark, a.OriginState, a.OriginRemark, a.SysState, a.SysRemark, a.OutMoneyState, a.OutMoneyRemark),
                                SysRemark = a.SysRemark,
                                SysStaffID = a.SysStaffID,
                                SysStaffName = eu5d.Name,
                                SysState = a.SysState,
                                SysTime = a.SysTime,
                                UserName = d.UserName,
                                SellStaffID = d.SellStaffID,
                                SellStaffName = eu6d.Name,
                                OrdersState=b.State
                            };
                    break;
                default:
                    break;
            }
            //默认给一个排序的字段
            if (entity.IsOwned == 1)
            {
                query = query.Where(p => p.OriginStaffID == staffid);
            }
            query = query.OrderBy(m => m.ID);
            List<OutMoneyOrdersRunningsListModel> l = query.ToList();
            foreach (var item in l)
            {
                item.StateRemark = GetOutMoneyOrdersRunningsStateRemark(item.OrdersState, item.FinanceState, item.FinanceRemark, item.OriginState, item.OriginRemark, item.SysState, item.StateRemark, item.OutMoneyState, item.OutMoneyRemark);
            }
            var result = new AjaxResult("成功", AjaxResultType.Success, l);
            return Token(result, "");
        }
        private string GetOutMoneyOrdersRunningsStateRemark(int State, int FinanceState, string FinanceReamrk, int OriginState, string OriginRemark, int SysState, string SysRemark, int OutMoneyState, string OutMoneyReamrk)
        {
            string s = "";
            if (State == 1) {
                s = "生成中";
            }
            else if(State==6)
            {
                s = "核算中";
            }
            else if (State==7)
            {
                s = "已完成";
            }
            else if (FinanceState == 0)
            {
                s = "财务审核中";
            }
            else if (FinanceState == 2)
            {
                s = FinanceReamrk;
            }
            else
            {
                if (OriginState == 0)
                {
                    s = "渠道审核中";
                }
                else if (OriginState == 2)
                {
                    s = OriginRemark;
                }
                else
                {
                    if (SysState == 0)
                    {
                        s = "管理审核中";
                    }
                    else if (SysState == 2)
                    {
                        s = SysRemark;
                    }
                    else
                    {
                        if (OutMoneyState == 0)
                        {
                            s = "出款中";
                        }
                        else if (OutMoneyState == 2)
                        {
                            s = OutMoneyReamrk;
                        }
                        else
                        {

                        }
                    }
                }
            }
            return s;
        }

        [Description("API-出款单审核")]
        public IHttpActionResult OutMoneyOrdersAuditing([FromBody]OutMoneyOrdersAuditingParamsModel entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            int staffid = BaseWebApiExt.GetStaffIDByToken();
            var model = SContract.GetByKey(staffid);
            var omo = OMOContract.GetByKey(entity.OutMoneyOrdersID);
            try
            {
                int count = 0;
                string[] ids = entity.IDs.Split(',');
                switch (omo.State)
                {
                    case 2://财务审核
                        if ((omo.ModuleID == 1 && IsAuthority(170)) || (omo.ModuleID == 2 && IsAuthority(207)) || (omo.ModuleID == 3 && IsAuthority(244)) || (omo.ModuleID == 4 && IsAuthority(284)))
                        {
                            count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == entity.OutMoneyOrdersID && p.FinanceState == 0 && ids.Contains(p.Id.ToString()), p => new OutMoneyOrdersRunnings { FinanceState = entity.State, FinanceRemark = entity.Remark, FinanceStaffID = model.Id, FinanceTime = DateTime.Now });
                            if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == entity.OutMoneyOrdersID && p.FinanceState == 0) == 0)
                            {
                                OMOContract.UpdateDirect(p => p.Id == entity.OutMoneyOrdersID, p => new OutMoneyOrders { State = 3 });
                            }
                        }
                        else
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "没有权限";
                            return Token(result, "");
                        }
                        break;
                    case 3://渠道审核
                        if ((omo.ModuleID == 1 && IsAuthority(171)) || (omo.ModuleID == 2 && IsAuthority(208)) || (omo.ModuleID == 3 && IsAuthority(245)) || (omo.ModuleID == 4 && IsAuthority(285)))
                        {
                            count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == entity.OutMoneyOrdersID && p.OriginState == 0 && p.FinanceState == 1 && ids.Contains(p.Id.ToString()) && p.OriginStaffID == model.Id, p => new OutMoneyOrdersRunnings { OriginState = entity.State, OriginRemark = entity.Remark, OriginTime = DateTime.Now });
                            if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == entity.OutMoneyOrdersID && p.OriginState == 0 && p.FinanceState == 1) == 0)
                            {
                                OMOContract.UpdateDirect(p => p.Id == entity.OutMoneyOrdersID, p => new OutMoneyOrders { State = 4 });
                            }
                        }
                        else
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "没有权限";
                            return Token(result, "");
                        }
                        break;
                    case 4://管理审核
                        if ((omo.ModuleID == 1 && IsAuthority(172)) || (omo.ModuleID == 2 && IsAuthority(209)) || (omo.ModuleID == 3 && IsAuthority(246)) || (omo.ModuleID == 4 && IsAuthority(286)))
                        {
                            count = OMORContract.UpdateDirect(p => p.OutMoneyOrdersID == entity.OutMoneyOrdersID && p.SysState == 0 && p.FinanceState == 1 && p.OriginState == 1 && ids.Contains(p.Id.ToString()), p => new OutMoneyOrdersRunnings { SysState = entity.State, SysRemark = entity.Remark, SysStaffID = model.Id, SysTime = DateTime.Now });
                            if (OMORContract.Entities.Count(p => p.OutMoneyOrdersID == entity.OutMoneyOrdersID && p.SysState == 0 && p.FinanceState == 1 && p.OriginState == 1) == 0)
                            {
                                OMOContract.UpdateDirect(p => p.Id == entity.OutMoneyOrdersID, p => new OutMoneyOrders { State = 5 });
                            }
                        }
                        else
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "没有权限";
                            return Token(result, "");
                        }
                        break;
                    default:
                        break;
                }
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "操作失败";
            }
            return Token(result, "");
        }

    }
}